package com.crazymaker.agent.demo.aop;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.instrument.Instrumentation;

import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith;

public class Agent {
    private static final Logger LOGGER = LoggerFactory.getLogger(AopTransformer.class);
    private final static String scanPackage = "com.crazymaker.circle.agent.biz";

    /**
     * 第一个阶段：注册的阶段
     * 第二个阶段： 增强的阶段
     * @param args
     * @param instrumentation  字节码的编写 ，  字节码的增强，字节码的仪表， jvm插桩
     */
    public static void premain(String args, Instrumentation instrumentation) {
        LOGGER.info(">>>>> ByteBuddyAgentDemo - premain()");
        // 对Greeting类字节码进行增强转换
        Listener listener = new Listener(scanPackage);


        final ByteBuddy byteBuddy = new ByteBuddy().with(TypeValidation.of(false));
        new AgentBuilder.Default(byteBuddy)
                .type(nameStartsWith(scanPackage))
                .transform(new AopTransformer(scanPackage)) // update the byte code
                .with(listener)
                .installOn(instrumentation);
    }
}